<template>
  <div class="login_box">
    <el-form ref="ruleFormRef" :model="data.ruleForm" status-icon :rules="rules" class="demo-ruleForm" label-width="70px">
      <h2>后台管理系统</h2>
      <el-form-item label="账号：" prop="username">
        <el-input v-model="data.ruleForm.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="data.ruleForm.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item class="login-btn">
        <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup="props, context" lang="ts">
import { reactive,ref } from 'vue'
import {LoginData} from '../type/login'
import type { FormInstance } from 'element-plus'
import {login} from "../request/api"
import { useRouter } from 'vue-router'

const data = reactive(new LoginData())
const rules = {
    username:[
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 5, message: '账号长度在3到10之间', trigger: 'blur' },
  ],
    password:[
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '密码长度在3到10之间', trigger: 'blur' },
  ],
  }
// 登录
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // 对表单的内容进行验证
  // vaild布尔类型，为true表示验证成功，反之异常
  formEl.validate((valid) => {
    if (valid) {
      // console.log('submit!')
      login(data.ruleForm).then((res)=>{
        // 将token进行保存
        localStorage.setItem('token',res.data.token)
        // 跳转页面首页
        router.push('/')
      })
    } else {
      console.log('error submit!')
      return false
    }
  })
}
// 重置
const resetForm = ()=>{
  data.ruleForm.username = '',
  data.ruleForm.password = ''
}
</script>

<style lang="scss" scoped>
.login_box {
  width: 100%;
  height: 100%;
  background-image: url('../assets/LoginBG.jpg');
  background-size: 100% 200%;
  background-repeat: no-repeat;
  padding-top: 1px;
  overflow: hidden;
  .demo-ruleForm{
    width: 500px;
    margin: 200px auto;
    background: #eee;
    padding: 40px;
    border-radius: 20px;
    text-align: center;
  ::v-deep .el-form-item__content{
    display: flex;
    justify-content: space-between;
    .el-button{
      flex-grow: 1;
    }
  }
  h2{
    margin-bottom: 30px;
  }
  }
}
</style>
